#!/usr/bin/python
# -*- coding: utf-8 -*-
import omencore as omendaemon
import time
import multiprocessing.queues as mqueue

# tests module for the functions of the process module
def function_for_process(arg1, arg2):
    print "hello %s, %s" % (arg1, arg2)
    
def function_for_process2(input_queue, output_queue, time_slice):
    while True:
        try:
            message = input_queue.get_nowait()
            if message:
                output_queue.put_nowait("%s:%s" % (message, message))              
        except mqueue.Empty:
            if time_slice:
                time.sleep(time_slice)
        

def test_process_creation():
    '''Simple process creation '''
    omen_proc = omendaemon.DaemonFactory.get_daemon("MyProcess", None, (), omendaemon.DaemonType.PROCESS)
    assert omen_proc.name == "MyProcess"
    del omen_proc
    
def test_process_creation2():
    '''Simple process creation2: creation with parameters '''
    omen_proc = omendaemon.DaemonFactory.get_daemon("MyProcess", function_for_process, ("aa","bb",), omendaemon.DaemonType.PROCESS)
    assert omen_proc.name == "MyProcess"
    
def test_process_execution():
    ''' Proccess Execution '''
    in_queue = mqueue.Queue()
    out_queue = mqueue.Queue()
    omen_proc = omendaemon.DaemonFactory.get_daemon("MyProcess", function_for_process2, (in_queue, out_queue, 2,), omendaemon.DaemonType.PROCESS)
    omen_proc.start()
    assert omen_proc.is_alive()
    
    in_queue.put_nowait("a")
    in_queue.put_nowait("b")
    in_queue.put_nowait("c")
    result = out_queue.get(timeout=3)
    assert result == "a:a"
    result = out_queue.get(timeout=3)
    assert result == "b:b"
    result = out_queue.get(timeout=3)
    assert result == "c:c"
    
    omen_proc.terminate()
    omen_proc.join()
    assert not omen_proc.is_alive()
    del omen_proc
    
def test_thread_execution():
    ''' Thread Execution '''
    in_queue = mqueue.Queue()
    out_queue = mqueue.Queue()
    omen_proc = omendaemon.DaemonFactory.get_daemon("MyProcess", function_for_process2, (in_queue, out_queue, 2, ), omendaemon.DaemonType.THREAD)
    omen_proc.start()
    assert omen_proc.is_alive()
    
    in_queue.put_nowait("a")
    in_queue.put_nowait("b")
    in_queue.put_nowait("c")
    result = out_queue.get(timeout=3)
    assert result == "a:a"
    result = out_queue.get(timeout=3)
    assert result == "b:b"
    result = out_queue.get(timeout=3)
    assert result == "c:c"
    
#    omen_proc.stop()
#    omen_proc.join()
#    assert not omen_proc.is_alive()
    del omen_proc
    